/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.bofaconnectors.utils;

import Thor.API.Operations.tcEmailOperationsIntf;
import Thor.API.Operations.tcFormDefinitionOperationsIntf;
import Thor.API.Operations.tcFormInstanceOperationsIntf;
import Thor.API.Operations.tcObjectOperationsIntf;
import Thor.API.tcResultSet;
import com.thortech.util.logging.Logger;
import com.thortech.xl.dataaccess.tcDataProvider;
import com.thortech.xl.dataobj.util.tcEmailNotificationUtil;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.oimwrapper.connectors.OIMAdapterBase;
import org.oimwrapper.connectors.internal.OIMObjectFormUtilities;
import org.oimwrapper.connectors.internal.OIMUtilityGetter;

/**
 *
 */
public class MailUtils extends OIMAdapterBase {

    
    private static Logger localLogger = Logger.getLogger(MailUtils.class.getName());
    private tcDataProvider database;
    
    private tcFormInstanceOperationsIntf formInstOps;
    private tcFormDefinitionOperationsIntf formDefOps;
    private tcObjectOperationsIntf objectOp;
    private OIMObjectFormUtilities objFormUtils;
    
    public MailUtils(String LogCategory, tcDataProvider Database) throws Exception {
        super("ORG.OIMWRAPPER", Database);
        database = Database;
        
        try
        {
            formInstOps = (tcFormInstanceOperationsIntf)this.getUtility(Thor.API.Operations.tcFormInstanceOperationsIntf.class);
            formDefOps = (tcFormDefinitionOperationsIntf)this.getUtility(Thor.API.Operations.tcFormDefinitionOperationsIntf.class);
            objectOp = (tcObjectOperationsIntf)this.getUtility(Thor.API.Operations.tcObjectOperationsIntf.class);
            objFormUtils = OIMUtilityGetter.getObjectFormUtilities(logger, objectOp,formInstOps, formDefOps);
        }
        catch(Exception e)
        {
            localLogger.error("APIError",e);
            throw e;
        }
    }
    
    public MailUtils(tcDataProvider Database) throws Exception {
        this("ORG.OIMWRAPPER", Database);
        
    }
    
    public void dummyMethod()
    {
        
    }
    
    public String sendEmail(String objectInstanceKey,String emailDef)
    {
        try
        {
            Map objectForm = objFormUtils.getObjectFormValues(Long.parseLong(objectInstanceKey), true, null);
            localLogger.debug("Calling Mailer");
            sendStockEmail(emailDef,objectForm);
        }
        catch(Exception e)
        {
            localLogger.error("APIError",e);
            return "FAILURE:" + e.toString();
        }
        return "SUCCESS";
    }
    
    public String sendEmail(String objectInstanceKey,String emailDef,String requestId)
    {
        try
        {
            Map objectForm = objFormUtils.getObjectFormValues(Long.parseLong(objectInstanceKey), true, null);
            objectForm.put("RequestId",requestId);
            localLogger.debug("Calling Mailer");
            sendStockEmail(emailDef,objectForm);
        }
        catch(Exception e)
        {
            localLogger.error("APIError",e);
            return "FAILURE:" + e.toString();
        }
        return "SUCCESS";
    }
    
    public String sendEmail(long processInstanceKey,String emailDef)
    {
        
        return "SUCCESS";
    }
    
    private void sendStockEmail(String emailDef,Map variables) throws Exception
    {
        localLogger.debug("sendStockEmail...");
        localLogger.debug("emailDef:" + emailDef);
        localLogger.debug("Valiables:" + variables);
        
        long emdKey = findEmd(emailDef);
        if (emdKey <= 0)
        {
            throw new Exception("INVALID EMD:" + emailDef);
        }
        String emdStr = Long.toString(emdKey);
        try
        {
            tcEmailNotificationUtil tcMailUtil = new tcEmailNotificationUtil(database);
            String requestId = (String)variables.get("RequestId");
            if (requestId != null)
                tcMailUtil.constructEmail(emdStr,requestId);
            else
                tcMailUtil.constructEmail(emailDef);
            String body = tcMailUtil.getBody();
            body = replaceCustomVariables(body,variables);
            tcMailUtil.setBody(body);
            String fromAddr = (String)variables.get("FromAddress");
            if (fromAddr != null && fromAddr.trim().length() > 0)
                tcMailUtil.setFromAddress(fromAddr);
            String toAddr = (String)variables.get("ToAddress");
            if (toAddr == null || toAddr.trim().length() <= 0)
                localLogger.error("Invalid to Addr");
            else
                tcMailUtil.sendEmail(toAddr);
        }
        catch(Exception e)
        {
            localLogger.error("API Mail Error",e);
            throw e;
        }
    }
    
    private String replaceCustomVariables(String body,Map variables)
    {
        Set<String> varKeys = variables.keySet();
        String newBody = body;
        for(String k : varKeys)
        {
            String tokenName = "<" + k + ">";
            do
            {
                int pos = newBody.indexOf(tokenName);
                if (pos < 0)
                    break;
                String val = (String)variables.get(k);
                newBody = newBody.replace(tokenName,val);
            }
            while(true);
        }
        return newBody;
    }
    
    
    private long findEmd(String name)
    {
        long emdKey = -1L;
        try
        {
            HashMap filter = new HashMap();
            filter.put("Email Definition.Name",name);
            tcEmailOperationsIntf mailOp = (tcEmailOperationsIntf)this.getUtility(Thor.API.Operations.tcEmailOperationsIntf.class);
            tcResultSet rs = mailOp.findEmailDefinition(filter);
            int rowCount = rs.getRowCount();
            for(int i=0;i<rowCount;i++)
            {
                rs.goToRow(i);
                emdKey = rs.getLongValue("Email Definition.Key");
            }
            return emdKey;
            
            
        }
        catch(Exception e)
        {
            logger.error("APIError",e);
            return -1;
        }
        
        
    }
    
    public void printResultSet(tcResultSet rs)
    {
        try
        {
            String[] colNames = rs.getColumnNames();
            int rowCount = rs.getRowCount();
            for(int i=0;i<rowCount;i++)
            {
                rs.goToRow(i);
                logger.debug("Printing row:" + i);
                for(int c=0;c<colNames.length;c++)
                {
                    
                    logger.debug(colNames[c] + ":" + rs.getStringValue(colNames[c]));
                }
            }
            
        }
        catch(Exception e)
        {
            logger.error("API Error",e);
        }
    }
    
    
    

}
